package org.dyndns.anderlin.jmplayer.client.ui.binder;

import org.apache.log4j.Logger;
import org.dyndns.anderlin.jmplayer.model.Artist;
import org.dyndns.anderlin.jmplayer.service.ArtistService;
import org.springframework.binding.form.FormModel;
import org.springframework.richclient.form.binding.Binding;
import org.springframework.richclient.form.binding.support.AbstractBinder;
import org.springframework.richclient.form.binding.support.CustomBinding;

import javax.swing.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Map;
import java.util.Set;

/**
 * Binds
 */
public class ArtistListBinder extends AbstractBinder {

    private final Logger log = Logger.getLogger(this.getClass());

    private ArtistService artistService;

    public ArtistListBinder(ArtistService artistService) {
        super(Set.class);
        this.artistService = artistService;
    }

    protected JComponent createControl(Map context) {
        return new ArtistListComponent(artistService);
    }

    protected Binding doBind(JComponent control, FormModel formModel, String formPropertyPath, Map context) {
        final ArtistListComponent artistList = (ArtistListComponent) control;
        return new CustomBinding(formModel, formPropertyPath, Set.class) {

            /**
             * Called when the underlying property's value model value changes.
             */
            protected void valueModelChanged(Object newValue) {
                // the user has selected a new file, update the control
                artistList.setArtists((Set<Artist>) newValue);
            }

            protected JComponent doBindControl() {
                artistList.setArtists((Set<Artist>) getValue());
                artistList.addPropertyChangeListener("value", new PropertyChangeListener() {

                    public void propertyChange(PropertyChangeEvent evt) {
                        controlValueChanged(evt.getNewValue());
                    }
                });
                return artistList;
            }

            /**
             * Called when the read only state of the bound property changes.
             */
            protected void readOnlyChanged() {
                artistList.setEnabled(isEnabled() && !isReadOnly());
            }

            /**
             * Called when the enabled state of the bound property changes.
             */
            protected void enabledChanged() {
                artistList.setEnabled(isEnabled() && !isReadOnly());
            }
        };
    }


}
